#include <iostream>
#include <pthread.h>
#include <vector>
#include <unistd.h>

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* MasterCore(void* arg)
{
    sleep(3);
    std::cout << "master thread 开始工作..." << std::endl;
    std::string name = static_cast<const char*>(arg);

    while(true)
    {
        // pthread_cond_signal(&cond); // 唤醒其中一个队列首部的线程
        pthread_cond_broadcast(&cond); // 唤醒所有队列
        std::cout << "master 唤醒一个线程..." << std::endl;
        sleep(1);
    }
    return nullptr;
}

void StartMaster(std::vector<pthread_t> *tids_ptr)
{
    pthread_t tid;
    int n = pthread_create(&tid, nullptr, MasterCore, (void*)"Master Thread");
    if(n != 0)
        perror("Master Thread Create");
    std::cout << "create master success" << std::endl;
    tids_ptr->emplace_back(tid);
}


void* SlaverCore(void* arg)
{
    std::string name = static_cast<const char*>(arg);

    while(true)
    {
        // 1. 加锁
        pthread_mutex_lock(&mutex);
        // 2. 使用条件变量
        pthread_cond_wait(&cond, &mutex);
        std::cout << "当前被唤醒的线程: " << name << std::endl;

        // 3. 解锁
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

void StartSlaver(std::vector<pthread_t> *tids_ptr, int threadNum = 3)
{
    for(int i = 0; i < threadNum; i++)
    {
        char* name = new char[64];
        snprintf(name, 64, "slaver-%d", i + 1);
        pthread_t tid;

        int n = pthread_create(&tid, nullptr, SlaverCore, (void*)name);
        if(n != 0)
            perror("Slaver Thread Create");
        std::cout << "create slaver success: " << name << std::endl;
        tids_ptr->emplace_back(tid);
    }
    
}


void WaitThread(std::vector<pthread_t> &tids)
{
    for(auto& tid: tids)
    {
        pthread_join(tid, nullptr);
    }
}

int main()
{
    std::vector<pthread_t> tids; // 记录所有的线程id
    StartMaster(&tids);
    StartSlaver(&tids, 3);
    WaitThread(tids);
    return 0;
}